<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\admin\model\CouponCodeGoods;
use app\admin\model\CouponCodeClass;
use think\Db;
/**
 * 首页接口
 */
class Indexinfo extends Api
{
    protected $noNeedLogin = ['goodsList','chargingStationList',];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        parent::_initialize();
    }
	/*
	 * 权益商品分类列表
	*/
	public function goodsCategoryList()
	{
	    // $params = $this->params;
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}

	    $data = CouponCodeClass::where('is_enable', 1)
			  ->order('sort desc ,id desc')
			  ->field('id,name,type')
			  ->select(); 
		if ($data) {
			$this->success('获取成功', $data);
		}
		$this->error('请求失败');
	}
    /*
     * 列表
    */
    public function goodsList()
    {
        // $params = $this->params;
		if (!$this->request->isPost()) {
			return $this->error('提交方式不正确');
		}
		$params = $this->request->isPost();
		$where['is_enable'] = array('eq',1);
		if(isset($params['coupon_code_class_id']) && !empty($params['coupon_code_class_id'])){
			$where['coupon_code_class_id'] = array('eq',$params['coupon_code_class_id']);
			// $where[] = ['coupon_code_class_id', '=' , ];
		}
		$limit    = !empty($params['limit']) ? $params['limit'] : 10;
		$page     = !empty($params['page']) ? $params['page'] : 1;
		
        $data['list'] = CouponCodeGoods::where($where)
			  ->order('sort desc ,id desc')
			  ->field('id as goods_id,name,image,introduction,price,price1,goods_code')
			  ->select(); 
		$data['count']    = CouponCodeGoods::where($where)->count();
		if ($data) {
			$this->success('获取成功', $data);
		}
		$this->error('请求失败');
    }

    /*
     * 详情
     */
    public function goodsDetail()
    {
        if (!$this->request->isPost()) {
        	return $this->error('提交方式不正确');
        }
		$params = $this->request->post();
		if(!isset($params['goods_id']) || empty($params['goods_id'])){
			return $this->error('参数错误');
		}
		$data = $data = CouponCodeGoods::where('id', $params['goods_id'])
			->field('id,name,icon,image,introduction,describe,price,retail_price,price1,coupon_code_class_id')
			->find();
		// $img[0] = $data;
		// $data = imgStr($img, 'image');
		// $data = imgStr($img, 'icon');

		$this->success('获取成功', $data);
    }
	/*
	 * 电站列表
	 */
	public function chargingStationList()
	{
	    $city = $this->request->param('city');
		$charging_station_name = $this->request->param('charging_station_name');
		$lat = $this->request->param('lat');
		$lon = $this->request->param('lon');
		$distance = $this->request->param('distance', 30);
		$page = $this->request->param('page',1);
		$limit = $this->request->param('limit',10);
		if (!$lat && !$lon) {
			$this->error('定位不能为空！');
		}

		$where['is_del'] = array('eq',1);
		$where['status'] = array('eq',1);
		$where['state'] = array('eq',1);
		if (!empty($city) && isset($city)) {
			$where['city_id'] = array('eq',$city);
		}

		if (!empty($charging_station_name) && isset($charging_station_name)) {
			$where['charging_station_name|address'] = array('like','%' . $charging_station_name . '%');
		}

		if (!empty($distance) && isset($distance)) {
			//计算定位范围
			$distance = $this->getRange($lat, $lon, $distance * 1000);
			$where['latitude'] = array('EGT',$distance['minLat']);
			$where['latitude'] = array('ELT',$distance['maxLat']);
			$where['longitude'] = array('EGT',$distance['minLon']);
			$where['longitude'] = array('ELT',$distance['maxLon']);
		}
		$conn = Db::connect(config('database.xiaoxin'));
		$data = $conn->name('charging_station')->where($where)->group('address')->select();
		$datas['list'] = $this->distanceOrder($data,$lat, $lon,$page,$limit);
		$datas['totalcount'] = count($data);
		//return json(['code' => 1, 'msg' => '获取成功', 'time' => time(), 'data' => $datas, 'totalcount' => count($data)]);
		$this->success('获取成功',$datas);
	}
	/**
	 * 距离排序
	 * @param $data,$data
	 * @return $data
	 **/
	public function distanceOrder($data,$lat,$lon,$page,$limit)
	{
		if (!empty($data)) {
			foreach ($data as $k => &$v) {
				//$v = $this->dispose($v);
				$v['distances'] = $this->getDistance($lat, $lon, $v['latitude'], $v['longitude']);
			}
		}
		$distances = array_column($data,'distances');
		array_multisort($distances,SORT_ASC,$data);

		$data = array_slice($data,($page - 1) * $limit, $limit);
		return $data;
	}
	/**
	 * 求两个已知经纬度之间的距离,单位为km
	 * @param lng1,lng2 经度
	 * @param lat1,lat2 纬度
	 * @return float 距离，单位为m
	 **/
	public function getDistance($lat1,$lng1,$lat2,$lng2)
	{
		//将角度转为狐度
		$radLat1 = deg2rad($lat1);//deg2rad()函数将角度转换为弧度
		$radLat2 = deg2rad($lat2);
		$radLng1 = deg2rad($lng1);
		$radLng2 = deg2rad($lng2);
		$a = $radLat1 - $radLat2;
		$b = $radLng1 - $radLng2;
		$s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6371;
		return round($s*1000);
	}
	//计算范围，可以做搜索用户
    public function getRange($lat, $lon, $raidus)
    {
        define('PI', 3.1415926535898);
        define('EARTH_RADIUS', 6378.137);
        //计算纬度
        $degree = (24901 * 1609) / 360.0;
        $dpmLat = 1 / $degree;
        $radiusLat = $dpmLat * $raidus;
        $minLat = $lat - $radiusLat; //得到最小纬度
        $maxLat = $lat + $radiusLat; //得到最大纬度
        //计算经度
        $mpdLng = $degree * cos($lat * (PI / 180));
        $dpmLng = 1 / $mpdLng;
        $radiusLng = $dpmLng * $raidus;
        $minLng = $lon - $radiusLng; //得到最小经度
        $maxLng = $lon + $radiusLng; //得到最大经度
        //范围
        $range = array(
            'minLat' => $minLat,
            'maxLat' => $maxLat,
            'minLon' => $minLng,
            'maxLon' => $maxLng
        );
        return $range;
    }

}
